#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown to Word 转换器
将专业实习报告从Markdown格式转换为Word文档
"""

import re
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.shared import OxmlElement, qn

def add_hyperlink(paragraph, url, text):
    """添加超链接"""
    part = paragraph.part
    r_id = part.relate_to(url, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", is_external=True)
    
    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('r:id'), r_id)
    
    new_run = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    
    color = OxmlElement('w:color')
    color.set(qn('w:val'), '0000FF')
    rPr.append(color)
    
    u = OxmlElement('w:u')
    u.set(qn('w:val'), 'single')
    rPr.append(u)
    
    new_run.append(rPr)
    new_run.text = text
    
    hyperlink.append(new_run)
    paragraph._p.append(hyperlink)
    
    return hyperlink

def convert_md_to_word(md_file_path, word_file_path):
    """将Markdown文件转换为Word文档"""
    
    # 检查输出文件是否被占用，如果是则使用新文件名
    import os
    if os.path.exists(word_file_path):
        base_name = os.path.splitext(word_file_path)[0]
        extension = os.path.splitext(word_file_path)[1]
        counter = 1
        while os.path.exists(f"{base_name}_{counter}{extension}"):
            counter += 1
        word_file_path = f"{base_name}_{counter}{extension}"
    
    # 创建Word文档
    doc = Document()
    
    # 设置文档样式
    style = doc.styles['Normal']
    font = style.font
    font.name = '宋体'
    font.size = Pt(12)
    
    # 读取Markdown文件
    with open(md_file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 按行分割内容
    lines = content.split('\n')
    
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        
        if not line:
            # 空行
            i += 1
            continue
            
        elif line.startswith('# '):
            # 一级标题
            title = line[2:].strip()
            heading = doc.add_heading(title, level=1)
            heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
            
        elif line.startswith('## '):
            # 二级标题
            title = line[3:].strip()
            doc.add_heading(title, level=2)
            
        elif line.startswith('### '):
            # 三级标题
            title = line[4:].strip()
            doc.add_heading(title, level=3)
            
        elif line.startswith('#### '):
            # 四级标题
            title = line[5:].strip()
            doc.add_heading(title, level=4)
            
        elif line.startswith('##### '):
            # 五级标题
            title = line[6:].strip()
            doc.add_heading(title, level=5)
            
        elif line.startswith('**') and line.endswith('**：') or line.endswith('**:'):
            # 粗体标签（如：**学生姓名**：）
            p = doc.add_paragraph()
            bold_text = line.replace('**', '').replace('：', '：').replace(':', ':')
            run = p.add_run(bold_text)
            run.bold = True
            
        elif line.startswith('- **') or line.startswith('* **'):
            # 粗体列表项
            text = line[2:].strip() if line.startswith('- ') else line[2:].strip()
            p = doc.add_paragraph(style='List Bullet')
            
            # 处理粗体文本
            parts = re.split(r'(\*\*.*?\*\*)', text)
            for part in parts:
                if part.startswith('**') and part.endswith('**'):
                    run = p.add_run(part[2:-2])
                    run.bold = True
                else:
                    p.add_run(part)
                    
        elif line.startswith('- ') or line.startswith('* '):
            # 普通列表项
            text = line[2:].strip()
            p = doc.add_paragraph(text, style='List Bullet')
            
        elif line.startswith('```'):
            # 代码块开始
            i += 1
            code_lines = []
            while i < len(lines) and not lines[i].strip().startswith('```'):
                code_lines.append(lines[i])
                i += 1
            
            # 添加代码块
            if code_lines:
                code_text = '\n'.join(code_lines)
                p = doc.add_paragraph(code_text)
                p.style = 'No Spacing'
                for run in p.runs:
                    run.font.name = 'Courier New'
                    run.font.size = Pt(10)
            
        elif line.startswith('|') and '|' in line[1:]:
            # 表格开始
            table_lines = [line]
            i += 1
            
            # 收集表格行
            while i < len(lines) and lines[i].strip().startswith('|'):
                table_lines.append(lines[i].strip())
                i += 1
            i -= 1  # 回退一行
            
            # 解析表格
            if len(table_lines) >= 2:
                # 解析表头
                headers = [cell.strip() for cell in table_lines[0].split('|')[1:-1]]
                
                # 跳过分隔行
                data_rows = []
                for row_line in table_lines[2:]:
                    if row_line.strip():
                        row_data = [cell.strip() for cell in row_line.split('|')[1:-1]]
                        data_rows.append(row_data)
                
                # 创建表格
                if data_rows:
                    table = doc.add_table(rows=1, cols=len(headers))
                    table.style = 'Table Grid'
                    
                    # 添加表头
                    hdr_cells = table.rows[0].cells
                    for idx, header in enumerate(headers):
                        if idx < len(hdr_cells):
                            hdr_cells[idx].text = header
                            hdr_cells[idx].paragraphs[0].runs[0].bold = True
                    
                    # 添加数据行
                    for row_data in data_rows:
                        row_cells = table.add_row().cells
                        for idx, cell_data in enumerate(row_data):
                            if idx < len(row_cells):
                                row_cells[idx].text = cell_data
                                
        elif line.startswith('---'):
            # 分隔线，添加分页符
            doc.add_page_break()
            
        else:
            # 普通段落
            if line:
                p = doc.add_paragraph()
                
                # 处理粗体、斜体等格式
                parts = re.split(r'(\*\*.*?\*\*|\*.*?\*|`.*?`)', line)
                for part in parts:
                    if part.startswith('**') and part.endswith('**'):
                        # 粗体
                        run = p.add_run(part[2:-2])
                        run.bold = True
                    elif part.startswith('*') and part.endswith('*') and not part.startswith('**'):
                        # 斜体
                        run = p.add_run(part[1:-1])
                        run.italic = True
                    elif part.startswith('`') and part.endswith('`'):
                        # 行内代码
                        run = p.add_run(part[1:-1])
                        run.font.name = 'Courier New'
                        run.font.size = Pt(10)
                    else:
                        # 普通文本
                        p.add_run(part)
        
        i += 1
    
    # 保存文档
    doc.save(word_file_path)
    print(f"转换完成！Word文档已保存到: {word_file_path}")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) != 3:
        print("使用方法: python md_to_word.py <markdown文件路径> <输出word文件路径>")
        sys.exit(1)
    
    md_file = sys.argv[1]
    word_file = sys.argv[2]
    
    print(f"正在转换: {md_file} -> {word_file}")
    
    try:
        convert_md_to_word(md_file, word_file)
        print(f"转换成功！Word文档已保存至: {word_file}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        import traceback
        traceback.print_exc()